package services

import (
	"encoding/json"
	"fmt"
	"net/http"

	"game_process_monitor/jobs"
	"game_process_monitor/util"

	"github.com/go-kit/log/level"
)

type ProcessStatus struct{}

func (p *ProcessStatus) Start() {
	level.Info(util.Logger).Log("starting processStatus at", "::7988")
	//log.Println("ProcessStatus start at", "::7988")
	http.HandleFunc("/v1/api/process/status", processStatus)
	http.ListenAndServe(":7988", nil)
}
func (p *ProcessStatus) Stop() {
	fmt.Println("stop")
}

// processStatus 返回进程信息的handler func
func processStatus(writer http.ResponseWriter, request *http.Request) {
	if request.Method != "GET" {
		writer.Write([]byte("get only!"))
		return
	}
	resMap := make([]map[string]interface{}, 0)
	// mapItem := goCahce.Items()
	mapItem := jobs.GoCache.Items()
	for k, v := range mapItem {
		m := make(map[string]interface{})
		m["processName"] = k
		m["runningNum"] = v.Object.([]int)[0]
		m["stoppedNum"] = v.Object.([]int)[1]
		//fmt.Println("m = ", m)
		resMap = append(resMap, m)
	}
	msg, _ := json.Marshal(resMap)
	level.Info(util.Logger).Log("process message", string(msg))
	//log.Println(string(msg))
	writer.Write(msg)
}
